"""
项目中心：所有项目信息
"""
from django.shortcuts import render, HttpResponse, redirect
from sa import models
# 分页器
from Utils.pagination import Pagination
from datetime import datetime, timedelta
from django.http import JsonResponse
from django.conf import settings
import csv


def platform(request):
    if request.sa.role not in settings.ROLE_LIST:
        return redirect('index')

    today = datetime.now().date()
    before = today - timedelta(days=60)

    data_dict = {}

    if request.sa.role != 'G_M':
        region = request.sa.RO
        data_dict['sa__RO'] = region

    get_sr_name = request.GET.get('SR_name', '')
    if get_sr_name:
        data_dict['SR_No__contains'] = get_sr_name

    get_sa = request.GET.get('owner_sa', '')
    if get_sa:
        data_dict['sa__SA_CName__contains'] = get_sa

    get_status = request.GET.get('p_status')
    # 前端表单定义了一个all, 当值为all时，不将此表单属性增加到 data_dict字典
    if get_status is not None and get_status != 'all':
        data_dict['status'] = get_status

    get_start_date = request.GET.get('start_d', '')
    if get_start_date:
        data_dict['start_date__gte'] = get_start_date
    else:
        data_dict['start_date__gte'] = before

    get_end_date = request.GET.get('end_d', '')
    if get_end_date:
        data_dict['end_date__lte'] = get_end_date

    get_project_name = request.GET.get('p_name', '')
    if get_project_name:
        data_dict['customer__name__contains'] = get_project_name

    get_big_project = request.GET.get('big_p')
    # print('大项目：', get_big_project, type(get_big_project))
    # 复选框被选中时，默认发送值'on'到服务器。
    # 可以自定义值，复选框添加一个value属性，例如<input type="checkbox" value="yes" >。
    if get_big_project == 'on':
        # 布尔类型需要转化为 True 或 False
        data_dict['big_project'] = True

    print(f'data_dict: {data_dict}')

    queryset = models.Project.objects.filter(**data_dict).order_by('-id')

    # 实例化分页对象
    page_object = Pagination(request, queryset, page_size=10)
    context = {
        'queryset': page_object.page_queryset,
        'count': queryset.count(),
        'page_string': page_object.html(),
        'data_dict': data_dict,

    }
    return render(request, 'center.html', context=context)


def export_project(request):
    if request.method == 'GET':
        # 创建一个查询使用的空字典
        data_dict = {}
        # 判断用户RO, 如果role不是GM,增加RO到查询字典
        if request.sa.role != 'G_M':
            region = request.sa.RO
            data_dict['sa__RO'] = region

        s_date = request.GET.get('exp_project_s_date', '')
        if s_date:
            data_dict['start_date__gte'] = s_date

        e_date = request.GET.get('exp_project_e_date', '')
        if e_date:
            data_dict['end_date__lte'] = e_date

        queryset = models.Project.objects.filter(**data_dict).order_by('-id')

        response = HttpResponse(
            # 类型csv, 不写就是html
            content_type="text/csv",
            # 指定headers, 附件和生成的文件名
            headers={"Content-Disposition": 'attachment; filename="project-list.csv"'},
        )
        # 在 请求标头的 User-Agent 里检查 是否有Windows字符，如果有改变码为utf-8-sig,
        # 否则 Windows系统 显示中文是乱码
        if 'Windows' in request.headers.get('User-Agent'):
            response.charset = 'utf-8-sig'
            # 构建一个csv 写入器，传入的参数为response
        writer = csv.writer(response)
        # 写入第一行内容
        writer.writerow(["SR#", '客户名称', "OwnerSA", "工作分类", "software", '服务器数量',
                         'MFD数量', '打印机数量', '开始日期', '结束日期', '状态'])
        for obj in queryset:
            writer.writerow([obj.SR_No, obj.customer, obj.sa, obj.category,
                             obj.software, obj.server_num, obj.mfd_num, obj.printer_num,
                             obj.start_date, obj.end_date, obj.status])
        return response


def project_info(request, p_id):
    project_obj = models.Project.objects.filter(id=p_id).first()
    if project_obj:
        context = {
            'project_obj': project_obj,
        }
        task_id = request.GET.get('task_id')
        if task_id and task_id.isdecimal():
            task_obj = models.Task.objects.filter(id=task_id, project=project_obj).first()
            if task_obj:
                context.update({'task_obj': task_obj})
            else:
                print(f'根据task_id: {task_id} , 没以找到对象')
        return render(request, 'browse.html', context=context)
    else:
        return redirect('center_platform')


def tasklist(request, p_id):
    project_obj = models.Project.objects.filter(id=p_id).first()
    if project_obj:
        task_queryset = models.Task.objects.filter(
            project=project_obj).order_by('-id').values('id', 'task_number')
        if task_queryset:
            return JsonResponse({'status': True, 'data': list(task_queryset)})
        else:
            return JsonResponse({'status': False, 'error_info': 'Task暂时不存在'})
